模型层(单表练习)
图书管理系统:
实现功能:book单表的增删改查
查询操作练习:
1
查询人民出版社出版过的价格大于
200
的书籍
2
查询
2017
年
8
月出版的所有以py开头的书籍名称
3
查询价格为
50
,
100
或者
150
的所有书籍名称及其出版社名
4
查询价格在
100
到
200
之间的所有书籍名称及其价格
5
查询所有人民出版社出版的书籍的价格(从高到低排序,去重)
效果:
目录结构:
06 django模型层\book\book\settings.py
1 """ 2 Django settings for book project. 3 4 Generated by 'django-admin startproject' using Django 2.2.3. 5 6 For more information on this file, see 7 https://docs.djangoproject.com/en/2.2/topics/settings/ 8 9 For the full list of settings and their values, see 10 https://docs.djangoproject.com/en/2.2/ref/settings/ 11 """ 12 13 import os 14 15 # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 18 19 # Quick-start development settings - unsuitable for production 20 # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 21 22 # SECURITY WARNING: keep the secret key used in production secret! 23 SECRET_KEY = 'cex-c#ja^@=p_dp#ak0-@=^ws!_-f6g#*52jb5!3%xhe4!dc^*' 24 25 # SECURITY WARNING: don't run with debug turned on in production! 26 DEBUG = True 27 28 ALLOWED_HOSTS = [] 29 30 31 # Application definition 32 33 INSTALLED_APPS = [ 34 'django.contrib.admin', 35 'django.contrib.auth', 36 'django.contrib.contenttypes', 37 'django.contrib.sessions', 38 'django.contrib.messages', 39 'django.contrib.staticfiles', 40 # 'book_app01.apps.BookApp01Config', 41 'book_app01', 42 ] 43 44 MIDDLEWARE = [ 45 'django.middleware.security.SecurityMiddleware', 46 'django.contrib.sessions.middleware.SessionMiddleware', 47 'django.middleware.common.CommonMiddleware', 48 'django.middleware.csrf.CsrfViewMiddleware', 49 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 'django.contrib.messages.middleware.MessageMiddleware', 51 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 ] 53 54 ROOT_URLCONF = 'book.urls' 55 56 TEMPLATES = [ 57 { 58 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 'DIRS': [os.path.join(BASE_DIR, 'templates')], 60 'APP_DIRS': True, 61 'OPTIONS': { 62 'context_processors': [ 63 'django.template.context_processors.debug', 64 'django.template.context_processors.request', 65 'django.contrib.auth.context_processors.auth', 66 'django.contrib.messages.context_processors.messages', 67 ], 68 }, 69 }, 70 ] 71 72 WSGI_APPLICATION = 'book.wsgi.application' 73 74 75 # Database 76 # https://docs.djangoproject.com/en/2.2/ref/settings/#databases 77 78 # DATABASES = { 79 # 'default': { 80 # 'ENGINE': 'django.db.backends.sqlite3', 81 # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 82 # } 83 # } 84 85 86 # Password validation 87 # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 88 89 AUTH_PASSWORD_VALIDATORS = [ 90 { 91 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 }, 93 { 94 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 }, 96 { 97 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 }, 99 {100 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',101 },102 ]103 104 105 # Internationalization106 # https://docs.djangoproject.com/en/2.2/topics/i18n/107 108 LANGUAGE_CODE = 'en-us'109 110 TIME_ZONE = 'UTC'111 112 USE_I18N = True113 114 USE_L10N = True115 116 USE_TZ = True117 118 119 # Static files (CSS, JavaScript, Images)120 # https://docs.djangoproject.com/en/2.2/howto/static-files/121 122 STATIC_URL = '/static/'123 124 STATICFILES_DIRS = [125 os.path.join(BASE_DIR, 'statics')126 ]127 DATABASES = {128 'default': {129 'ENGINE': 'django.db.backends.mysql',130 'NAME':'orm',# 要连接的数据库,连接前需要创建好131 'USER':'root',# 连接数据库的用户名132 'PASSWORD':'root',# 连接数据库的密码133 'HOST':'127.0.0.1',# 连接主机,默认本级134 'PORT':3306 # 端口 默认3306135 }136 }137 138 LOGGING = {139 'version': 1,140 'disable_existing_loggers': False,141 'handlers': {142 'console':{143 'level':'DEBUG',144 'class':'logging.StreamHandler',145 },146 },147 'loggers': {148 'django.db.backends': {149 'handlers': ['console'],150 'propagate': True,151 'level':'DEBUG',152 },153 }154 }
06 django模型层\book\book\__init__.py
import pymysqlpymysql.install_as_MySQLdb()
06 django模型层\book\book\urls.py
from django.contrib import adminfrom django.urls import path,re_path,includeurlpatterns = [ path('admin/', admin.site.urls), re_path('^app01/', include(('book_app01.urls','book_app01'))),]
06 django模型层\book\book_app01\models.py
from django.db import models# Create your models here.class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=32,unique=True) state = models.BooleanField() pub_date = models.DateField() price=models.DecimalField(max_digits=8,decimal_places=2) publish=models.CharField(max_length=32) def __str__(self): return self.title
06 django模型层\book\book_app01\urls.py
from django.urls import path,re_path,includefrom book_app01 import viewsurlpatterns = [ path('book/', views.book), path('book/add', views.add_book), re_path(r'book/(\d+)/update', views.update_book), re_path(r'book/(\d+)/delete', views.delete_book),]
06 django模型层\book\book_app01\views.py
1 from django.shortcuts import render,redirect 2 from book_app01.models import Book 3 4 # Create your views here. 5 6 7 def book(request): 8 method = request.method 9 req = request.POST if request.POST else request.GET10 try:11 title = req.get('title') if req.get('title') else ''12 except:13 title = ''14 book_list = Book.objects.filter(title__contains=title)15 '''16 # 1 查询人民出版社出版过的价格大于200的书籍17 res = Book.objects.filter(publish="人民出版社",price__gt=200)18 # 2 查询2017年8月出版的所有以py开头的书籍名称19 res = Book.objects.filter(pub_date__contains="2017-08",title__startswith='py').values('title')20 # 3 查询价格为50,100或者150的所有书籍名称及其出版社名21 res = Book.objects.filter(price__in=[50,100,150]).values('title','publish')22 # 4 查询价格在100到200之间的所有书籍名称及其价格23 res = Book.objects.filter(price__range=[100,200]).values('title','price')24 # 5 查询所有人民出版社出版的书籍的价格(从高到低排序,去重)25 res = Book.objects.filter(publish="人民出版社").values('price').distinct().order_by('-price')26 print('res----------->',res)27 '''28 return render(request, 'book.html',locals())29 30 31 def add_book(request):32 method = request.method33 if method == 'POST':34 req = request.POST35 title = req['title'].strip()36 price = req['price'].strip()37 date = req['date'].strip()38 publish = req['publish'].strip()39 if title and price and date and publish:40 selct_res = Book.objects.filter(title=title)41 if not selct_res:42 Book.objects.create(title=title,price=price,pub_date=date,publish=publish)43 return redirect('/app01/book')44 opt_res = '书籍【%s】已存在,请修改后提交!'%title45 else:46 opt_res = '输入不能为空,请修改后提交!'47 return render(request, 'addbook.html', locals())48 49 50 def update_book(request, num):51 select_res = Book.objects.filter(id=num)52 if select_res:53 method = request.method54 book_obj = select_res[0]55 if method == 'POST':56 req = request.POST57 title = req['title'].strip()58 price = req['price'].strip()59 date = req['date'].strip()60 publish = req['publish'].strip()61 if title and price and date and publish:62 selct_res = Book.objects.exclude(id=num).filter(title=title)63 if not selct_res:64 Book.objects.filter(id=num).update(title=title, price=price, pub_date=date, publish=publish)65 return redirect('/app01/book')66 opt_res = '书籍【%s】已存在,请修改后提交!' % selct_res[0].title67 else:68 opt_res = '输入不能为空,请修改后提交!'69 return render(request, 'updatebook.html', locals())70 return redirect('/app01/book')71 72 def delete_book(request, num=None):73 select_res = Book.objects.filter(id=num)74 if select_res:75 Book.objects.filter(id=num).delete()76 return redirect('/app01/book')
06 django模型层\book\templates\advertise.html
123202019进击的菜鸟45 web框架开发 678 crm&爬虫 91011 算法&设计模式&企业应用121314 vue项目151617 复习python&自动化&性能181921262020进击的小鸟2223 fighting!242527322021进击的大鸟2829 go on !3031
06 django模型层\book\templates\base.html
1 2 3 4 5 {% block title %} 6base——title 7 {% endblock title %} 8 10 {% block style %}11 26 {% endblock style %}27 28 29 30 31 32 333445 46 47 {% block js %}48 49 {% endblock js %}50354436 {% include 'advertise.html' %}373839 {% block content%}4043base_content
41 {% endblock %}42
06 django模型层\book\templates\book.html
1 {% extends 'base.html' %} 2 3 {% block style %} 4 { { block.super }} 5 24 {% endblock style %}25 26 {% block title %}27book 28 {% endblock title %}29 30 {% block content %}31查看书籍
32 33 78 {% endblock content %}
06 django模型层\book\templates\addbook.html
1 {% extends 'base.html' %} 2 3 {% block style %} 4 { { block.super }} 5 17 {% endblock style %}18 19 {% block title %}20book 21 {% endblock title %}22 23 {% block content %}24新增书籍
25 262756 {% endblock content %}285529 5254{
{ opt_res }}53
06 django模型层\book\templates\updatebook.html
1 {% extends 'base.html' %} 2 3 {% block style %} 4 { { block.super }} 5 17 {% endblock style %}18 19 {% block title %}20book 21 {% endblock title %}22 23 {% block content %}24修改书籍
25 262756 {% endblock content %}285529 5254{
{ opt_res }}53